package file_operation;

import java.io.*;

public class FileCopy {
    private String sourcePath;  // 源路径
    private String targetPath;  // 目标路径
    private int k;              // 表示文件的第几行，0表示不插入内容
    private String addContent;  // 在第k行插入的内容
    private boolean replace;    // 表示是否替换，为true则是用新内容替换第k行内容

    public FileCopy(String sourcePath, String targetPath, int k, String addContent, boolean replace) {
        this.sourcePath = sourcePath;
        this.targetPath = targetPath;
        this.k = Math.max(k, 0);
        this.addContent = addContent;
        this.replace = replace;
    }

    public void startCopy(){
        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            System.out.println("源路径不存在!");
            return;
        }
        File[] files = null;
        if (sourceFile.isFile()) {
            files = new File[1];
            files[0] = sourceFile;
        }
        else
            files = sourceFile.listFiles();     // 获取当前目录下的所有文件及目录
        if (files != null) {
            File tp = new File(targetPath);
            if (!tp.isFile() && tp.mkdirs())
                System.out.println("创建目录：" + tp.getPath());
            for (File file : files) {
                File targetFile = new File(targetPath + "\\" + file.getName());
                try (BufferedReader reader = BufferedReadWrite.getReader(file);
                     BufferedWriter writer = BufferedReadWrite.getWriter(targetFile)) {
                    String buffer;
                    int i = 1;
                    while ((buffer = reader.readLine()) != null) {
                        if(i++ == k) {
                            writer.write(addContent + '\n');
                            if (replace)
                                continue;
                        }
                        writer.write(buffer + "\n");
                    }
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String sourcePath = "D:\\Projects\\JavaDemo\\src\\PracticalProjects\\games\\SubmarineWar_V2";
//        String targetPath = "D:\\test";
        String targetPath = "D:\\Projects\\SubmarineWar\\src\\cn\\tedu\\submarine";
        String addContent = "package cn.tedu.submarine;";
        FileCopy fc = new FileCopy(sourcePath, targetPath, 1, addContent, true);
        fc.startCopy();
    }
}
